<?php
/**
 * Created by PhpStorm.
 * User: qixiuxiu
 * Date: 2017/4/6
 * Time: 14:29
 */
require_once __DIR__ . '/../vendor/autoload.php';//包容这个文件，可以允许类被自动加载

use Symfony\Component\HttpFoundation\Request;//引入请求类
use Symfony\Component\HttpFoundation\Response;//引入返回类
use Symfony\Component\Routing;//引入routing路由
use Symfony\Component\HttpKernel;//引入控制器解析器

//渲染模板
function render_template($request){
    extract($request->attributes->all(),EXTR_SKIP);
    ob_start();
    include sprintf(__DIR__.'/../src/pages/%s.php',$_route);
    return new Response(ob_get_clean());//获取当前缓冲区内容到response并删除当前的输出缓冲区
}
$request = Request::createFromGlobals();//createFromGlobals()方法基于当前PHP全局变量创建了一个Request对象。
$routes = include __DIR__ . '/../src/app.php';//获得路由配置文件

//UrlMatcher实例能够匹配URL路径
$context = new Routing\RequestContext();
$context->fromRequest($request);
$matcher = new Routing\Matcher\UrlMatcher($routes,$context);

//使用HttpKernel的控制器解析器（controller resolver）和参数解析器ArgumentResolver
$controllerResolver = new HttpKernel\Controller\ControllerResolver();
$argumentResolver = new HttpKernel\Controller\ArgumentResolver();

//URL matcher在匹配不到路由时会抛出一个异常
try{
    /*
    *渲染的完成依靠的是一个外部函数（render_template()） 对它传入提取自URL的属性（attributes）。*/
    $request->attributes->add($matcher->match($request->getPathInfo()));

    //获得与请求相关联的Controller实例
    $controller = $controllerResolver->getController($request);
    //获得传递给控制器的参数。
    $arguments = $argumentResolver->getArguments($request, $controller);

    //call_user_func_array — 调用回调函数callback，并把一个数组参数作为回调函数的参数
    $response = call_user_func_array($controller, $arguments);
}catch (Routing\Exception\ResourceNotFoundException $e){
    $response = new Response('Not Found',404);
}catch (Exception $e){
    $response = new Response('an error occurred',500);//500错误现已被正确管理；
}

$response->send();
